<template>
  <div class="login">
    <div class="login_box">
      <el-form ref="loginFromRef" class="login_from" :rules="rules" :model="loginFrom">
        <el-form-item prop="username">
          <el-input v-model="loginFrom.username"  prefix-icon="el-icon-user-solid" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input type="password" v-model="loginFrom.password"  prefix-icon="el-icon-s-tools" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item class="btns">
          <el-button type="primary" @click="login">登陆</el-button>
        </el-form-item>
      </el-form>
      
    </div>
  </div>
</template>

<script>
export default {
  data(){
    // 验证规则
    var validateUserName = (rule, value, callback) =>{
        if (value === '') {
          callback(new Error('请输入用户名'));
        }else{
            callback();
        }
    }
    var validatePassWord = (rule, value, callback) =>{
        if (value === '') {
          callback(new Error('请输入密码'));
        }else{
            callback();
        }
    }
    return{
      //登陆表单
    loginFrom:{
      username:'admin',
      password:'123456'
    },
    //验证规则
    rules:{
        username:[
            {       
                validator:validateUserName,
                trigger:"blur"
            }
        ],
        password:[
            {
                validator:validatePassWord,
                trigger:"blur"
            }
        ]
      }
    }
  },
  methods:{
    login(){
      this.$refs.loginFromRef.validate(async valid => {
        if (!valid) {
          return
        }
        const {data:res} = await this.$http.post("login",this.loginFrom)
        if (res.meta.status!==200) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg); 
        sessionStorage.setItem("token",res.data.token);
        this.$router.push('/home')
      })
    }
  }
};
</script>

<style lang="less" scoped>
.login {
  height: 100%;
  .login_box {
    width: 400px;
    height: 300px;
    border: 1px solid #ccc;
    border-radius: 15px;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    .login_from{
      position: absolute;
      margin-top: 60px;
      padding: 0 20px;
      width:100%;
      
    }
    .btns{
      display: flex;
      justify-content: flex-end;
    }
  }
}
</style>
